'use client'

import React from 'react'
import { Button, Result, Alert } from 'antd'
import { ReloadOutlined, HomeOutlined, SettingOutlined } from '@ant-design/icons'
import { errorHandler, ErrorType, ErrorSeverity } from '@/lib/errorHandler'

interface ViewerErrorBoundaryState {
    hasError: boolean
    error: Error | null
    errorInfo: React.ErrorInfo | null
    retryCount: number
}

interface ViewerErrorBoundaryProps {
    children: React.ReactNode
    viewerType?: '2D' | '3D'
    onReset?: () => void
    maxRetries?: number
}

export class ViewerErrorBoundary extends React.Component<
    ViewerErrorBoundaryProps,
    ViewerErrorBoundaryState
> {
    private maxRetries: number

    constructor(props: ViewerErrorBoundaryProps) {
        super(props)
        this.maxRetries = props.maxRetries || 3
        this.state = {
            hasError: false,
            error: null,
            errorInfo: null,
            retryCount: 0
        }
    }

    static getDerivedStateFromError(error: Error): Partial<ViewerErrorBoundaryState> {
        return { hasError: true, error }
    }

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
        this.setState({
            error,
            errorInfo
        })

        // 使用错误处理器记录查看器错误
        errorHandler.handleError(error, {
            type: ErrorType.VIEWER_ERROR,
            severity: ErrorSeverity.HIGH,
            context: {
                viewerType: this.props.viewerType,
                componentStack: errorInfo.componentStack,
                retryCount: this.state.retryCount
            },
            showNotification: false // 由错误边界自己处理UI
        })
    }

    handleRetry = () => {
        if (this.state.retryCount < this.maxRetries) {
            this.setState(prevState => ({
                hasError: false,
                error: null,
                errorInfo: null,
                retryCount: prevState.retryCount + 1
            }))

            // 调用重置回调
            if (this.props.onReset) {
                this.props.onReset()
            }
        }
    }

    handleReset = () => {
        this.setState({
            hasError: false,
            error: null,
            errorInfo: null,
            retryCount: 0
        })

        if (this.props.onReset) {
            this.props.onReset()
        }
    }

    handleGoHome = () => {
        window.location.href = '/'
    }

    handleRefresh = () => {
        window.location.reload()
    }

    render() {
        if (this.state.hasError) {
            const canRetry = this.state.retryCount < this.maxRetries
            const viewerTypeText = this.props.viewerType === '3D' ? '3D查看器' : '2D查看器'

            return (
                <div className="viewer-error-boundary h-full flex items-center justify-center bg-gray-50">
                    <div className="max-w-lg w-full p-6">
                        <Result
                            status="error"
                            title={`${viewerTypeText}出现错误`}
                            subTitle={`很抱歉，${viewerTypeText}遇到了意外错误。您可以尝试重新加载或返回主页。`}
                            extra={[
                                canRetry && (
                                    <Button
                                        type="primary"
                                        key="retry"
                                        icon={<ReloadOutlined />}
                                        onClick={this.handleRetry}
                                    >
                                        重试 ({this.maxRetries - this.state.retryCount} 次剩余)
                                    </Button>
                                ),
                                <Button
                                    key="reset"
                                    icon={<SettingOutlined />}
                                    onClick={this.handleReset}
                                >
                                    重置查看器
                                </Button>,
                                <Button
                                    key="refresh"
                                    onClick={this.handleRefresh}
                                >
                                    刷新页面
                                </Button>,
                                <Button
                                    key="home"
                                    icon={<HomeOutlined />}
                                    onClick={this.handleGoHome}
                                >
                                    返回主页
                                </Button>
                            ].filter(Boolean)}
                        />

                        {/* 错误详情 */}
                        {this.state.error && (
                            <Alert
                                message="错误详情"
                                description={
                                    <div className="text-sm">
                                        <div className="mb-2">
                                            <strong>错误类型:</strong> {this.state.error.name}
                                        </div>
                                        <div className="mb-2">
                                            <strong>错误消息:</strong> {this.state.error.message}
                                        </div>
                                        <div>
                                            <strong>重试次数:</strong> {this.state.retryCount}/{this.maxRetries}
                                        </div>
                                    </div>
                                }
                                type="error"
                                showIcon
                                className="mt-4"
                            />
                        )}

                        {/* 开发环境显示详细信息 */}
                        {process.env.NODE_ENV === 'development' && this.state.error && (
                            <details className="mt-4 p-4 bg-red-50 border border-red-200 rounded">
                                <summary className="cursor-pointer font-medium text-red-800">
                                    开发调试信息 (点击展开)
                                </summary>
                                <div className="mt-2 text-sm">
                                    <div className="mb-2">
                                        <strong>错误堆栈:</strong>
                                        <pre className="mt-1 text-red-600 text-xs whitespace-pre-wrap overflow-auto max-h-32">
                                            {this.state.error.stack}
                                        </pre>
                                    </div>
                                    {this.state.errorInfo && (
                                        <div>
                                            <strong>组件堆栈:</strong>
                                            <pre className="mt-1 text-red-600 text-xs whitespace-pre-wrap overflow-auto max-h-32">
                                                {this.state.errorInfo.componentStack}
                                            </pre>
                                        </div>
                                    )}
                                </div>
                            </details>
                        )}

                        {/* 故障排除建议 */}
                        <div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded">
                            <h4 className="font-medium text-blue-800 mb-2">故障排除建议:</h4>
                            <ul className="text-sm text-blue-700 space-y-1">
                                <li>• 检查网络连接是否正常</li>
                                <li>• 确认影像文件格式是否支持</li>
                                <li>• 尝试刷新页面或清除浏览器缓存</li>
                                <li>• 如果问题持续存在，请联系技术支持</li>
                            </ul>
                        </div>
                    </div>
                </div>
            )
        }

        return this.props.children
    }
}

export default ViewerErrorBoundary